package user

import (
	"gitee.com/xiaoyutab/gatway/config"
	"gitee.com/xiaoyutab/gatway/model"
	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/xerror"
)

// 查询用户信息
//
//	username	登录用户名
func GetInfoByUserName(username string) (*model.User, error) {
	if username == "" {
		return nil, xerror.New("登录账户不能为空")
	}
	info := model.User{}
	cache_key := xcache.Key("service.user.get.info.by.username", username)
	if xcache.Exists(cache_key) {
		if err := xcache.GetStruct(cache_key, &info); err == nil {
			return &info, nil
		}
	}
	// 连接数据库进行查询
	err := config.DB.Table(info.TableName()).
		Where("username", username).
		Find(&info).
		Error
	if err != nil {
		return nil, xerror.To(err)
	}
	if info.Id > 0 {
		xcache.SetStruct(xcache.Key("service.user.get.info.by.id", info.Id), info)
		xcache.SetStruct(cache_key, info)
	}
	return &info, nil
}
